﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using YY.UI.BaseDataSvc;
using YY.Common;

namespace YY.UI
{
    public partial class EditFeeFrm : BaseFrm
    {
        /// <summary>
        /// 费用所属工作单
        /// </summary>
        public TB_Order Order { get; set; }

        /// <summary>
        /// 编辑模式时传入id
        /// </summary>
        public int ID { get; set; }

        /// <summary>
        /// 费用临时变量
        /// </summary>
        TB_Fee _Fee = null;

        /// <summary>
        /// 通用分类数据临时变量
        /// </summary>
        IEnumerable<TB_Options> options = null;

        /// <summary>
        /// 指定窗体费用类型
        /// </summary>
        public EnumCommon.FeeType FeeType { get; set; }

        /// <summary>
        /// 客户源数据临时变量
        /// </summary>
        IEnumerable<TB_Clients> clients = null;

        /// <summary>
        /// 用户源数据临时变量
        /// </summary>
        IEnumerable<TB_User> users = null;

        /// <summary>
        /// 是否编辑模式
        /// </summary>
        public bool EditMode { get; set; }

        public EditFeeFrm()
        {
            InitializeComponent();
            this.BaseDataProxy = new YY.UI.BaseDataSvc.BaseDataClient();
        }

        private void EditFeeFrm_Load(object sender, EventArgs e)
        {
            this.BaseDataProxy.Open();
            Common.BindEnumToComboBox(this.cbBoxFeeType, typeof(EnumCommon.FeeType), this.FeeType.ToString());
            this.users = this.BaseDataProxy.FindUsers(null, null);
            this.clients = this.BaseDataProxy.FindClients(null, null, null, null, null);
            this.options = this.BaseDataProxy.FindOptions(null, null, null);


            bindTarget();

            Common.BindOptionsComboBox(this.cbBoxItem, this.options, EnumCommon.OptionType.费目类型);
            this.cbBoxItem.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);

            Common.BindOptionsComboBox(this.cbBoxUnit, this.options, EnumCommon.OptionType.币制单位);
            this.cbBoxUnit.SelectedItem = this.cbBoxUnit.Items.Cast<TB_Options>().SingleOrDefault(p => p.name == Common.BIZ_GetSysParamValue(EnumCommon.SysParamType.DefaultUnit) && p.type == EnumCommon.OptionType.币制单位.ToString());//默认选择人民币
            this.cbBoxUnit.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);

            Common.ComboBoxBindDatas<TB_User>(this.cbBoxOperator, this.users, "userName", "id");
            this.cbBoxOperator.SelectedItem = this.users.SingleOrDefault(p => p.id == SysLoginUserInfo.UserId);
            this.cbBoxOperator.KeyPress += new KeyPressEventHandler(cbBoxOperator_KeyPress);

            if (this.EditMode)
                bindData(this.ID);

            this.cbBoxFeeType.Enabled = false;

            if (this.Order != null)
                this.lblCode.Text = "工作单号：" + this.Order.code;
        }

        private void bindTarget()
        {
            if (this.FeeType == EnumCommon.FeeType.应收)
            {
                Common.ComboBoxBindDatas<TB_Clients>(this.cbBoxTarget, this.clients, "fullName", "id");
                this.cbBoxTarget.SelectedItem = this.clients.SingleOrDefault(p => p.id == this.Order.client);
                this.cbBoxTarget.KeyPress -= new KeyPressEventHandler(optionCbBox_KeyPress);
                this.cbBoxTarget.KeyPress += new KeyPressEventHandler(cbBoxTarget_KeyPress);
            }
            else
            {
                Common.BindOptionsComboBox(this.cbBoxTarget, this.options, EnumCommon.OptionType.结算对象);
                this.cbBoxTarget.KeyPress -= new KeyPressEventHandler(cbBoxTarget_KeyPress);
                this.cbBoxTarget.KeyPress += new KeyPressEventHandler(optionCbBox_KeyPress);
            }
        }

        private void bindData(int id)
        {
            this._Fee = this.BaseDataProxy.GetFee(id);
            if (this._Fee != null)
            {
                this.txtBoxAmount.Text = this._Fee.amount.ToString();
                this.txtBoxCode.Text = this._Fee.code;
                Common.SelectedOptionsComboBox(this.cbBoxItem, this.options, EnumCommon.OptionType.费目类型, this._Fee.item);
                this.txtBoxMemo.Text = this._Fee.memo;
                this.ckBoxIsVerify.Checked = this._Fee.isVerify;
                if (this._Fee.isVerify)
                {
                    this.lblVerifyMan.Text = "审批人：" + this.users.First(p => p.id == this._Fee.verifyMan).userName;
                    this.lblVerifyTime.Text = "审批时间：" + Convert.ToDateTime(this._Fee.verifyTime).ToString("yyyy-MM-dd hh:mm:dd");
                }
                this.cbBoxFeeType.SelectedItem = Enum.GetName(typeof(EnumCommon.FeeType), this._Fee.feeType);

                if (this._Fee.target != null)
                {
                    if (this.FeeType == EnumCommon.FeeType.应收)
                        this.cbBoxTarget.SelectedItem = this.clients.SingleOrDefault(p => p.id == this._Fee.target);
                    else
                        this.cbBoxTarget.SelectedItem = this.options.SingleOrDefault(p => p.id == this._Fee.target);
                }

                if (this._Fee.unit != null)
                    Common.SelectedOptionsComboBox(cbBoxUnit, this.options, EnumCommon.OptionType.币制单位, this._Fee.unit);
                this.cbBoxOperator.SelectedItem = this.users.SingleOrDefault(p => p.id == this._Fee.@operator);
                this.dtpOPTime.Value = this._Fee.opTime;
                if (this._Fee.isVerify)
                    this.tsBtnVerify.Text = "反审批";
            }
        }

        private void cbBoxTarget_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cbBox = sender as ComboBox;
                if (this.clients != null)
                {
                    TB_Clients[] datas = this.clients.Where(p => p.fullName.Contains(cbBox.Text) || p.shortName.Contains(cbBox.Text)).ToArray();
                    Common.ComboBoxMatchClient(cbBox, datas, this);
                }
            }
        }

        /// <summary>
        /// 通用分类选择框回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void optionCbBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cbBox = sender as ComboBox;
                EnumCommon.OptionType ot = (EnumCommon.OptionType)cbBox.Tag;
                if (this.options != null)
                {
                    TB_Options[] os = this.options.Where(p => p.type == ot.ToString()).Where(p => p.name.Contains(cbBox.Text) || p.code.Contains(cbBox.Text)).ToArray();
                    Common.ComboBoxMatchOption(cbBox, os, this, ot);
                }
            }
        }

        private void cbBoxOperator_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                ComboBox cbBox = sender as ComboBox;
                if (this.users != null)
                {
                    TB_User[] users = this.users.Where(p => p.userName.Contains(cbBox.Text) || p.code.Contains(cbBox.Text)).ToArray();
                    Common.ComboBoxMatchUser(cbBox, users, this);
                }
            }
        }

        private void tsBtnAdd_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.groupBox1.Controls.Count; i++)
            {
                if (this.groupBox1.Controls[i].Name.StartsWith("txtBox"))
                    this.groupBox1.Controls[i].Text = null;
            }

            this.EditMode = false;
            this.ID = 0;
        }

        private void tsBtnSave_Click(object sender, EventArgs e)
        {
            if (SysLoginUserInfo.Role == (int)EnumCommon.SysRoleType.财务员)
            {
                if (Common.BIZ_OrderIsClosed(this.Order.id))
                {
                    MessageBox.Show("已收款结束单据不能修改！");
                    return;
                }
            }
            else
            {
                if (Common.BIZ_OrderIsSubmit(this.Order.id))
                {
                    MessageBox.Show("已提交财务审核单据不能修改！");
                    return;
                }
            }

            if (this.cbBoxItem.SelectedItem == null)
            {
                MessageBox.Show("请选择费目名称！");
                this.cbBoxItem.Focus();
                return;
            }

            if (this.cbBoxTarget.SelectedItem == null)
            {
                MessageBox.Show("请选择费用结算对象！");
                this.cbBoxTarget.Focus();
                return;
            }

            if (string.IsNullOrEmpty(this.txtBoxAmount.Text))
            {
                MessageBox.Show("请输入金额！");
                this.txtBoxAmount.Focus();
                return;
            }

            if (this.cbBoxOperator.SelectedItem == null)
            {
                MessageBox.Show("请选择制单人！");
                this.cbBoxOperator.Focus();
                return;
            }

            TB_Fee f = new TB_Fee();
            f.amount = Convert.ToDecimal(this.txtBoxAmount.Text);
            f.code = this.txtBoxCode.Text;
            f.item = (this.cbBoxItem.SelectedItem as TB_Options).id;
            f.memo = this.txtBoxMemo.Text;
            f.@operator = (this.cbBoxOperator.SelectedItem as TB_User).id;
            f.opTime = this.dtpOPTime.Value;

            if (this.cbBoxUnit.SelectedItem != null)
                f.unit = (this.cbBoxUnit.SelectedItem as TB_Options).id;

            if (this.cbBoxTarget.SelectedItem != null)
                if (this.FeeType == EnumCommon.FeeType.应收)
                    f.target = (this.cbBoxTarget.SelectedItem as TB_Clients).id;
                else
                    f.target = (this.cbBoxTarget.SelectedItem as TB_Options).id;
            Common.OperateType opType = Common.OperateType.Add;
            bool ok = false;
            if (this.EditMode)
            {
                if (this.Order.isSubmit)
                {
                    MessageBox.Show("已提交财务审核的费用不能修改！");
                    return;
                }

                f.id = this._Fee.id;
                f.feeType = this._Fee.feeType;
                f.createTime = this._Fee.createTime;
                f.isVerify = this._Fee.isVerify;
                f.verifyMan = this._Fee.verifyMan;
                f.verifyTime = this._Fee.verifyTime;
                f.order = this._Fee.order;
                opType = Common.OperateType.Update;
                ok = this.BaseDataProxy.UpdateFee(f);
            }
            else
            {
                TB_Fee[] fees = this.BaseDataProxy.GetFees(this.Order.id);
                if (fees.Any(p => p.feeType == (short)this.FeeType && p.item == (this.cbBoxItem.SelectedItem as TB_Options).id))
                {
                    MessageBox.Show("已存在相同的费目！");
                    return;
                }

                f.order = this.Order.id;
                f.feeType = (short)this.FeeType;
                f.createTime = DateTime.Now;

                this.ID = this.BaseDataProxy.AddFee(f);
                ok = this.ID > 0;
                f.id = this.ID;
            }

            if (ok)
            {
                this._Fee = f;
                this.EditMode = true;
                this.ID = this._Fee.id;
                CommonEventArg<TB_Fee> arg = new CommonEventArg<TB_Fee>(f, opType);
                if (this.FeeType == EnumCommon.FeeType.应收)
                    YY.Common.EventCommon.OnYSUdDGVEvnt(sender, arg);
                else
                    YY.Common.EventCommon.OnYFUdDGVEvnt(sender, arg);
            }
            else
                MessageBox.Show("保存异常！");

        }

        private void tsBtnDelete_Click(object sender, EventArgs e)
        {
            if (SysLoginUserInfo.Role == (int)EnumCommon.SysRoleType.财务员)
            {
                if (Common.BIZ_OrderIsClosed(this.Order.id))
                {
                    MessageBox.Show("已收款结束单据不能删除！");
                    return;
                }
            }
            else
            {
                if (Common.BIZ_OrderIsSubmit(this.Order.id))
                {
                    MessageBox.Show("已提交财务审核单据不能删除！");
                    return;
                }
            }

            if (this.EditMode && this._Fee != null)
            {

                if (MessageBox.Show("确认删除该项吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    if (this.BaseDataProxy.DeleteFee(this._Fee.id))
                    {
                        CommonEventArg<TB_Fee> arg = new CommonEventArg<TB_Fee>(this._Fee, Common.OperateType.Delete);
                        if (this.FeeType == EnumCommon.FeeType.应收)
                            YY.Common.EventCommon.OnYSUdDGVEvnt(sender, arg);
                        else
                            YY.Common.EventCommon.OnYFUdDGVEvnt(sender, arg);
                        MessageBox.Show("费用资料已删除！");
                        this.Close();
                    }
                    else
                        MessageBox.Show("删除异常！");
                }
            }
        }

        /// <summary>
        /// 费用审批
        /// </summary>
        /// <param name="isVerify">是否批准</param>
        /// <returns></returns>
        private bool verifyFee(bool isVerify)
        {
            if (this.Order.financier != SysLoginUserInfo.UserId)
            {
                MessageBox.Show("对该单据没有审核权限！");
                return false;
            }

            if (this.EditMode && this._Fee != null)
            {
                this._Fee.isVerify = isVerify;
                this._Fee.verifyMan = SysLoginUserInfo.UserId;
                this._Fee.verifyTime = DateTime.Now;
                if (this.BaseDataProxy.UpdateFee(this._Fee))
                    return true;
            }
            return false;
        }

        private void txtBoxAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13 && e.KeyChar != 45 && e.KeyChar != 46)
                e.Handled = true;

            //输入为负号时，只能输入一次且只能输入一次
            if (e.KeyChar == 45 && (((TextBox)sender).SelectionStart != 0 || ((TextBox)sender).Text.IndexOf("-") >= 0)) 
                e.Handled = true;
            if (e.KeyChar == 46 && ((TextBox)sender).Text.IndexOf(".") >= 0) 
                e.Handled = true;
        }

        private void tsBtnVerify_Click(object sender, EventArgs e)
        {
            string msg = this._Fee.isVerify ? "反审批" : "批准";
            if (MessageBox.Show("确认" + msg + "该费用吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                if (verifyFee(!this._Fee.isVerify))
                {
                    CommonEventArg<TB_Fee> arg = new CommonEventArg<TB_Fee>(this._Fee, Common.OperateType.Update);
                    if (this.FeeType == EnumCommon.FeeType.应收)
                        YY.Common.EventCommon.OnYSUdDGVEvnt(sender, arg);
                    else
                        YY.Common.EventCommon.OnYFUdDGVEvnt(sender, arg);
                    MessageBox.Show("费用已" + msg);
                    this.bindData(this._Fee.id);
                }

        }
    }
}
